import { Model, DataTypes, Optional } from 'sequelize';
import { sequelize } from '../../config/database';
import Room from './Room';

// 直播场次接口
interface LiveSessionAttributes {
  id: string;
  roomId: string;
  title?: string | null;
  startTime?: Date;
  endTime?: Date | null;
  createdAt?: Date;
  updatedAt?: Date;
}

// 创建时可选的属性
interface LiveSessionCreationAttributes extends Optional<LiveSessionAttributes, 'id' | 'createdAt' | 'updatedAt'> {}

// 直播场次模型类
class LiveSession extends Model<LiveSessionAttributes, LiveSessionCreationAttributes> implements LiveSessionAttributes {
  declare id: string;
  declare roomId: string;
  declare title: string | null;
  declare startTime: Date;
  declare endTime: Date | null;
  
  // 时间戳
  declare readonly createdAt: Date;
  declare readonly updatedAt: Date;
}

// 初始化模型
LiveSession.init(
  {
    id: {
      type: DataTypes.STRING,
      primaryKey: true,
      defaultValue: DataTypes.UUIDV4
    },
    roomId: {
      type: DataTypes.STRING,
      allowNull: false
    },
    title: {
      type: DataTypes.STRING,
      allowNull: true
    },
    startTime: {
      type: DataTypes.DATE,
      allowNull: false,
      defaultValue: DataTypes.NOW
    },
    endTime: {
      type: DataTypes.DATE,
      allowNull: true
    }
  },
  {
    sequelize,
    tableName: 'live_sessions',
    modelName: 'LiveSession',
    timestamps: true,
    indexes: [
      {
        fields: ['roomId', 'startTime']
      }
    ]
  }
);

// 设置关联关系（禁用外键约束）
LiveSession.belongsTo(Room, { foreignKey: 'roomId', as: 'room', constraints: false });
Room.hasMany(LiveSession, { foreignKey: 'roomId', as: 'sessions', constraints: false });

export default LiveSession;